#include "KgTestLogDb.h"
#include "QuFile.h"

namespace kPrivate
{
    // 将"yyyy-MM-dd hh-mm-ss"格式的文件名解析为考核时间
    static QDateTime string2DataTime(const QString& str)
    {
        auto tokens = str.split(' ', Qt::SkipEmptyParts);
        if (tokens.size() != 2)
            return QDateTime();

        auto date = tokens[0].split('-');
        if (date.size() != 3)
            return QDateTime();

        auto time = tokens[1].split('-');
        if (time.size() != 3)
            return QDateTime();

        return QDateTime(QDate(date[0].toInt(), date[1].toInt(), date[2].toInt()),
                         QTime(time[0].toInt(), time[1].toInt(), time[2].toInt()));
    }

    static QString dataTime2String(const QDateTime& dt)
    {
        return dt.toString("yyyy-MM-dd hh-mm-ss");
    }
}


KgTestLogDb::KgTestLogDb(const QString& logDir) : logDir_(logDir)
{

}

QString KgTestLogDb::historyFilePath_() const
{
    return logDir_ + "/history.log";
}

QString KgTestLogDb::detailFilePath_(const QDateTime& dt) const
{
    return logDir_ + "/" + kPrivate::dataTime2String(dt) + ".log";
}

bool KgTestLogDb::appendHistory(const KpTestInfo& info)
{
    return QuFile::appendLine(historyFilePath_(), info.toLine());
}

QVector<KpTestInfo> KgTestLogDb::loadHistoryList() const
{
    auto hl = QuFile::readLines(historyFilePath_());
    QVector<KpTestInfo> res; res.reserve(hl.size());
    for (auto& i : hl) {
        KpTestInfo info;
        if (info.fromLine(i))
            res.emplace_back(std::move(info));
    }

    return res;
}

QVector<KgTestLogDb::KpTestDetail> KgTestLogDb::loadDetails(const QDateTime& dt) const
{
    return QuFile::readTextMatrix<4>(detailFilePath_(dt));
}

bool KgTestLogDb::saveDetails(const QDateTime& dt, const QVector<KpTestDetail>& tds)
{
    return QuFile::writeTextMatrix(tds, detailFilePath_(dt));
}
